package user;

import product.Movie;
import product.SaleRecord;
import product.Show;
import remember.LogUtil;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

public class ManagerService {
    private List<Movie> movies = new ArrayList<>();
    private List<Show> shows = new ArrayList<>();
    private List<SaleRecord> saleRecords = new ArrayList<>();
    private User currentManager;
    private Scanner scanner = new Scanner(System.in);
    private AdminService adminService;
    private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
    private int showIdCounter = 1000; // 场次ID计数器

    public ManagerService(AdminService adminService) {
        this.adminService = adminService;
        initTestData();
    }

    private void initTestData() {
        // 初始化测试影片
        movies.add(new Movie("流浪地球", "郭帆", "吴京,屈楚萧", "太阳即将毁灭，人类开启流浪地球计划", 125, 9.0, true));
        movies.add(new Movie("满江红", "张艺谋", "沈腾,易烊千玺", "南宋年间的悬疑故事", 159, 8.5, true));

        // 初始化测试场次
        try {
            Date showTime = sdf.parse("2024-05-20 19:30");
            shows.add(new Show(++showIdCounter, movies.get(0), "1号厅", showTime, 50.0, 6, 12));
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }

    // 添加影片
    private void addMovie() {
        System.out.println("\n=== 添加新影片 ===");

        System.out.print("请输入片名：");
        String name = scanner.nextLine().trim();

        // 检查片名是否已存在
        for (Movie m : movies) {
            if (m.getName().equals(name)) {
                System.out.println("错误：该影片已存在");
                return;
            }
        }

        System.out.print("请输入导演：");
        String director = scanner.nextLine().trim();

        System.out.print("请输入主演（用逗号分隔）：");
        String actors = scanner.nextLine().trim();

        System.out.print("请输入剧情简介：");
        String intro = scanner.nextLine().trim();

        int duration = 0;
        while (true) {
            System.out.print("请输入时长（分钟）：");
            try {
                duration = Integer.parseInt(scanner.nextLine().trim());
                if (duration > 0) break;
                System.out.println("时长必须为正数");
            } catch (NumberFormatException e) {
                System.out.println("请输入有效数字");
            }
        }

        double score = 0;
        while (true) {
            System.out.print("请输入评分（0-10分）：");
            try {
                score = Double.parseDouble(scanner.nextLine().trim());
                if (score >= 0 && score <= 10) break;
                System.out.println("评分必须在0-10之间");
            } catch (NumberFormatException e) {
                System.out.println("请输入有效数字");
            }
        }

        // 创建并添加影片
        Movie newMovie = new Movie(name, director, actors, intro, duration, score, true);
        movies.add(newMovie);
        System.out.println("影片添加成功！");
    }

    // 修改影片
    private void updateMovie() {
        System.out.println("\n=== 修改影片 ===");
        System.out.print("请输入要修改的影片名称：");
        String name = scanner.nextLine().trim();

        Movie target = null;
        for (Movie m : movies) {
            if (m.getName().equals(name)) {
                target = m;
                break;
            }
        }

        if (target == null) {
            System.out.println("未找到该影片");
            return;
        }

        System.out.print("请输入新片名（不修改请回车）：");
        String newName = scanner.nextLine().trim();
        if (!newName.isEmpty()) {
            // 检查新片名是否已存在
            boolean exists = false;
            for (Movie m : movies) {
                if (m.getName().equals(newName) && !m.getName().equals(name)) {
                    exists = true;
                    break;
                }
            }
            if (exists) {
                System.out.println("错误：新片名已存在");
                return;
            }
            target.setName(newName);
        }

        System.out.print("请输入新导演（不修改请回车）：");
        String director = scanner.nextLine().trim();
        if (!director.isEmpty()) target.setDirector(director);

        System.out.print("请输入新主演（不修改请回车）：");
        String actors = scanner.nextLine().trim();
        if (!actors.isEmpty()) target.setActors(actors);

        System.out.print("请输入新剧情简介（不修改请回车）：");
        String intro = scanner.nextLine().trim();
        if (!intro.isEmpty()) target.setIntro(intro);

        System.out.print("请输入新时长（分钟，不修改请回车）：");
        String durationStr = scanner.nextLine().trim();
        if (!durationStr.isEmpty()) {
            try {
                int duration = Integer.parseInt(durationStr);
                if (duration > 0) target.setDuration(duration);
                else System.out.println("时长输入无效，未修改");
            } catch (NumberFormatException e) {
                System.out.println("时长输入无效，未修改");
            }
        }

        System.out.print("请输入新评分（0-10分，不修改请回车）：");
        String scoreStr = scanner.nextLine().trim();
        if (!scoreStr.isEmpty()) {
            try {
                double score = Double.parseDouble(scoreStr);
                if (score >= 0 && score <= 10) target.setScore(score);
                else System.out.println("评分输入无效，未修改");
            } catch (NumberFormatException e) {
                System.out.println("评分输入无效，未修改");
            }
        }

        System.out.println("影片信息修改完成！");
    }

    // 删除影片
    private void deleteMovie() {
        System.out.println("\n=== 删除影片 ===");
        System.out.print("请输入要删除的影片名称：");
        String name = scanner.nextLine().trim();

        Movie target = null;
        for (Movie m : movies) {
            if (m.getName().equals(name)) {
                target = m;
                break;
            }
        }

        if (target == null) {
            System.out.println("未找到该影片");
            return;
        }

        // 检查是否有排片
        for (Show s : shows) {
            if (s.getMovie().getName().equals(name)) {
                System.out.println("无法删除：该影片已有排片");
                return;
            }
        }

        System.out.print("删除后无法恢复，是否确认删除？(y/n)：");
        String confirm = scanner.nextLine().trim();
        if (confirm.equalsIgnoreCase("y")) {
            movies.remove(target);
            System.out.println("影片删除成功");
        } else {
            System.out.println("已取消删除");
        }
    }

    // 查询影片
    private void queryMovie() {
        System.out.println("\n=== 查询影片 ===");
        System.out.println("1.按片名查询 2.按导演查询 3.按主演查询 4.组合查询");
        System.out.print("请选择查询方式：");

        try {
            int choice = Integer.parseInt(scanner.nextLine().trim());
            List<Movie> result = new ArrayList<>();

            switch (choice) {
                case 1:
                    System.out.print("请输入片名：");
                    String name = scanner.nextLine().trim();
                    for (Movie m : movies) {
                        if (m.getName().contains(name)) result.add(m);
                    }
                    break;

                case 2:
                    System.out.print("请输入导演：");
                    String director = scanner.nextLine().trim();
                    for (Movie m : movies) {
                        if (m.getDirector().contains(director)) result.add(m);
                    }
                    break;

                case 3:
                    System.out.print("请输入主演：");
                    String actor = scanner.nextLine().trim();
                    for (Movie m : movies) {
                        if (m.getActors().contains(actor)) result.add(m);
                    }
                    break;

                case 4:
                    System.out.print("请输入片名（可为空）：");
                    String n = scanner.nextLine().trim();
                    System.out.print("请输入导演（可为空）：");
                    String d = scanner.nextLine().trim();
                    System.out.print("请输入主演（可为空）：");
                    String a = scanner.nextLine().trim();

                    for (Movie m : movies) {
                        boolean match = true;
                        if (!n.isEmpty() && !m.getName().contains(n)) match = false;
                        if (!d.isEmpty() && !m.getDirector().contains(d)) match = false;
                        if (!a.isEmpty() && !m.getActors().contains(a)) match = false;
                        if (match) result.add(m);
                    }
                    break;

                default:
                    System.out.println("无效选择");
                    return;
            }

            // 显示查询结果
            if (result.isEmpty()) {
                System.out.println("未找到符合条件的影片");
            } else {
                System.out.println("\n查询到" + result.size() + "部影片：");
                for (Movie m : result) {
                    m.displayInfo();
                    System.out.println("---------------------");
                }
            }
        } catch (NumberFormatException e) {
            System.out.println("请输入有效数字");
        }
    }

    // 增加场次
    private void addShow() {
        System.out.println("\n=== 增加场次 ===");

        // 显示可选影片
        System.out.println("可选影片：");
        for (int i = 0; i < movies.size(); i++) {
            System.out.println((i + 1) + "." + movies.get(i).getName());
        }
        System.out.print("请选择影片（序号）：");
        int movieIdx = -1;
        try {
            movieIdx = Integer.parseInt(scanner.nextLine().trim()) - 1;
            if (movieIdx < 0 || movieIdx >= movies.size()) {
                System.out.println("无效选择");
                return;
            }
        } catch (NumberFormatException e) {
            System.out.println("请输入有效数字");
            return;
        }
        Movie selectedMovie = movies.get(movieIdx);

        System.out.print("请输入放映厅（如：1号厅）：");
        String hall = scanner.nextLine().trim();

        // 日期校验（提前一周内）
        Date showTime = null;
        while (true) {
            System.out.print("请输入放映时间（格式：yyyy-MM-dd HH:mm）：");
            String timeStr = scanner.nextLine().trim();
            try {
                showTime = sdf.parse(timeStr);
                Date now = new Date();
                Date maxTime = new Date(now.getTime() + TimeUnit.DAYS.toMillis(7));

                if (showTime.before(now)) {
                    System.out.println("不能选择过去的时间");
                } else if (showTime.after(maxTime)) {
                    System.out.println("最多只能提前一周排片");
                } else {
                    break;
                }
            } catch (ParseException e) {
                System.out.println("时间格式错误，请重新输入");
            }
        }

        // 检查时间冲突
        for (Show s : shows) {
            if (s.getHall().equals(hall) &&
                    Math.abs(s.getTime().getTime() - showTime.getTime()) < 30 * 60 * 1000) { // 30分钟内视为冲突
                System.out.println("冲突：该放映厅此时间段已有排片");
                return;
            }
        }

        double price = 0;
        while (true) {
            System.out.print("请输入票价：");
            try {
                price = Double.parseDouble(scanner.nextLine().trim());
                if (price > 0) break;
                System.out.println("票价必须为正数");
            } catch (NumberFormatException e) {
                System.out.println("请输入有效数字");
            }
        }

        // 创建场次（6行12列座位）
        Show newShow = new Show(++showIdCounter, selectedMovie, hall, showTime, price, 6, 12);
        shows.add(newShow);
        System.out.println("场次添加成功！场次ID：" + newShow.getId());
    }

    // 修改场次
    private void updateShow() {
        System.out.println("\n=== 修改场次 ===");
        System.out.print("请输入要修改的场次ID：");
        int id = -1;
        try {
            id = Integer.parseInt(scanner.nextLine().trim());
        } catch (NumberFormatException e) {
            System.out.println("请输入有效数字");
            return;
        }

        Show target = null;
        for (Show s : shows) {
            if (s.getId() == id) {
                target = s;
                break;
            }
        }

        if (target == null) {
            System.out.println("未找到该场次");
            return;
        }

        // 检查是否有售票
        if (target.hasSoldTickets()) {
            System.out.println("无法修改：该场次已有售出的票");
            return;
        }

        // 记录原始信息用于日志
        String oldMovieName = target.getMovie().getName();
        Date oldTime = target.getTime();

        // 选择新影片
        System.out.println("可选影片：");
        for (int i = 0; i < movies.size(); i++) {
            System.out.println((i + 1) + "." + movies.get(i).getName());
        }
        System.out.print("请选择新影片（序号，不修改请回车）：");
        String movieChoice = scanner.nextLine().trim();
        if (!movieChoice.isEmpty()) {
            try {
                int idx = Integer.parseInt(movieChoice) - 1;
                if (idx >= 0 && idx < movies.size()) {
                    target.setMovie(movies.get(idx));
                } else {
                    System.out.println("无效选择，影片未修改");
                }
            } catch (NumberFormatException e) {
                System.out.println("输入无效，影片未修改");
            }
        }

        // 修改时间
        System.out.print("请输入新放映时间（格式：yyyy-MM-dd HH:mm，不修改请回车）：");
        String timeStr = scanner.nextLine().trim();
        if (!timeStr.isEmpty()) {
            try {
                Date newTime = sdf.parse(timeStr);
                Date now = new Date();
                if (newTime.before(now)) {
                    System.out.println("不能选择过去的时间，时间未修改");
                } else {
                    target.setTime(newTime);
                }
            } catch (ParseException e) {
                System.out.println("时间格式错误，时间未修改");
            }
        }

        System.out.println("场次修改成功");
        // 记录日志
        if (currentManager != null) {
            LogUtil.log(String.format("修改场次信息：场次ID=%d，原时间=%s，原片名=%s，新片名=%s",
                            id, sdf.format(oldTime), oldMovieName, target.getMovie().getName()),
                    currentManager.getUserName());
        }
    }

    // 删除场次
    private void deleteShow() {
        System.out.println("\n=== 删除场次 ===");
        System.out.print("请输入要删除的场次ID：");
        int id = -1;
        try {
            id = Integer.parseInt(scanner.nextLine().trim());
        } catch (NumberFormatException e) {
            System.out.println("请输入有效数字");
            return;
        }

        Show target = null;
        for (Show s : shows) {
            if (s.getId() == id) {
                target = s;
                break;
            }
        }

        if (target == null) {
            System.out.println("未找到该场次");
            return;
        }

        // 检查是否有售票
        if (target.hasSoldTickets()) {
            System.out.println("无法删除：该场次已有售出的票");
            return;
        }

        System.out.print("删除后无法恢复，是否确认删除？(y/n)：");
        String confirm = scanner.nextLine().trim();
        if (confirm.equalsIgnoreCase("y")) {
            shows.remove(target);
            System.out.println("场次删除成功");
            // 记录日志
            if (currentManager != null) {
                LogUtil.log(String.format("删除场次：场次ID=%d，片名=%s，时间=%s",
                                id, target.getMovie().getName(), sdf.format(target.getTime())),
                        currentManager.getUserName());
            }
        } else {
            System.out.println("已取消删除");
        }
    }

    // 列出场次
    private void listShows() {
        System.out.println("\n=== 场次列表 ===");
        System.out.println("1.近一周 2.当日 3.近3日");
        System.out.print("请选择时间范围：");
        int range = -1;
        try {
            range = Integer.parseInt(scanner.nextLine().trim());
            if (range < 1 || range > 3) {
                System.out.println("无效选择");
                return;
            }
        } catch (NumberFormatException e) {
            System.out.println("请输入有效数字");
            return;
        }

        Date now = new Date();
        Date start = now;
        Date end = new Date(now.getTime() + TimeUnit.DAYS.toMillis(7)); // 默认近一周

        if (range == 2) { // 当日
            Calendar cal = Calendar.getInstance();
            cal.setTime(now);
            cal.set(Calendar.HOUR_OF_DAY, 0);
            cal.set(Calendar.MINUTE, 0);
            cal.set(Calendar.SECOND, 0);
            start = cal.getTime();

            cal.set(Calendar.HOUR_OF_DAY, 23);
            cal.set(Calendar.MINUTE, 59);
            cal.set(Calendar.SECOND, 59);
            end = cal.getTime();
        } else if (range == 3) { // 近3日
            end = new Date(now.getTime() + TimeUnit.DAYS.toMillis(3));
        }

        // 筛选并显示场次
        List<Show> filtered = new ArrayList<>();
        for (Show s : shows) {
            if (s.getTime().after(start) && s.getTime().before(end)) {
                filtered.add(s);
            }
        }

        if (filtered.isEmpty()) {
            System.out.println("该时间范围内无场次");
            return;
        }

        // 按时间排序
        filtered.sort(Comparator.comparing(Show::getTime));

        System.out.println("\n共" + filtered.size() + "场：");
        for (Show s : filtered) {
            System.out.printf("场次ID：%d，影片：%s，放映厅：%s，时间：%s，票价：%.2f元，剩余座位：%d\n",
                    s.getId(), s.getMovie().getName(), s.getHall(),
                    sdf.format(s.getTime()), s.getPrice(),
                    s.getAvailableSeatsCount());
        }
    }

    // 自动排片
    private void autoArrangeShows() {
        System.out.println("\n=== 自动排片 ===");
        if (movies.isEmpty()) {
            System.out.println("无影片可排片");
            return;
        }

        // 按评分排序（高分优先）
        List<Movie> sortedMovies = new ArrayList<>(movies);
        sortedMovies.sort((m1, m2) -> Double.compare(m2.getScore(), m1.getScore()));

        // 黄金时段：周末19:00-21:00，工作日20:00-22:00
        Calendar baseCal = Calendar.getInstance();
        baseCal.setTime(new Date());
        baseCal.add(Calendar.DAY_OF_MONTH, 1); // 从明天开始排片

        int addedCount = 0;
        // 排未来3天的场次
        for (int day = 0; day < 3; day++) {
            Calendar cal = (Calendar) baseCal.clone();
            cal.add(Calendar.DAY_OF_MONTH, day);

            int weekDay = cal.get(Calendar.DAY_OF_WEEK);
            boolean isWeekend = (weekDay == Calendar.SATURDAY || weekDay == Calendar.SUNDAY);

            // 黄金时段
            int hour = isWeekend ? 19 : 20;
            cal.set(Calendar.HOUR_OF_DAY, hour);
            cal.set(Calendar.MINUTE, 0);
            cal.set(Calendar.SECOND, 0);

            // 为高分影片安排黄金时段
            if (addedCount < sortedMovies.size()) {
                Movie movie = sortedMovies.get(addedCount);
                String hall = (addedCount % 3 + 1) + "号厅"; // 轮流通放映厅

                // 检查冲突
                boolean conflict = false;
                for (Show s : shows) {
                    if (s.getHall().equals(hall) &&
                            Math.abs(s.getTime().getTime() - cal.getTimeInMillis()) < 30 * 60 * 1000) {
                        conflict = true;
                        break;
                    }
                }

                if (!conflict) {
                    Show newShow = new Show(++showIdCounter, movie, hall, cal.getTime(),
                            isWeekend ? 60.0 : 50.0, 6, 12);
                    shows.add(newShow);
                    addedCount++;
                    System.out.printf("自动排片：%s %s %s 场次ID：%d\n",
                            sdf.format(cal.getTime()), hall, movie.getName(), newShow.getId());
                }
            }
        }

        System.out.println("自动排片完成，共添加" + addedCount + "个场次");
    }

    // 查看销售数据主入口
    private void viewSalesData() {
        System.out.println("\n=== 查看销售数据 ===");
        System.out.println("1. 当日销售数据");
        System.out.println("2. 当周销售数据");
        System.out.println("3. 当月销售数据");
        System.out.print("请选择：");
        try {
            int choice = Integer.parseInt(scanner.nextLine().trim());
            switch (choice) {
                case 1:
                    viewDailySales();
                    break;
                case 2:
                    viewWeeklySales();
                    break;
                case 3:
                    viewMonthlySales();
                    break;
                default:
                    System.out.println("无效选择（1-3）");
            }
        } catch (NumberFormatException e) {
            System.out.println("请输入有效数字");
        }
    }

    // 查看当日销售数据
    private void viewDailySales() {
        System.out.println("\n=== 当日销售数据 ===");
        Date now = new Date();
        Calendar cal = Calendar.getInstance();
        cal.setTime(now);

        // 当日时间范围：00:00:00 至 23:59:59
        cal.set(Calendar.HOUR_OF_DAY, 0);
        cal.set(Calendar.MINUTE, 0);
        cal.set(Calendar.SECOND, 0);
        Date start = cal.getTime();

        cal.set(Calendar.HOUR_OF_DAY, 23);
        cal.set(Calendar.MINUTE, 59);
        cal.set(Calendar.SECOND, 59);
        Date end = cal.getTime();

        List<SaleRecord> dailySales = getSalesInRange(start, end);
        if (dailySales.isEmpty()) {
            System.out.println("当日无销售数据");
            return;
        }

        // 按场次分组统计
        Map<Show, List<SaleRecord>> showSalesMap = dailySales.stream()
                .collect(Collectors.groupingBy(SaleRecord::getShow));

        System.out.println("各场次销售数据：");
        for (Map.Entry<Show, List<SaleRecord>> entry : showSalesMap.entrySet()) {
            Show show = entry.getKey();
            List<SaleRecord> records = entry.getValue();

            int totalTickets = records.size();
            int refundTickets = 0;
            double refundAmount = 0;
            double totalPrice = 0;

            for (SaleRecord record : records) {
                totalPrice += record.getPrice();
                if (record.isRefunded()) {
                    refundTickets++;
                    refundAmount += record.getRefundAmount();
                }
            }
            int soldTickets = totalTickets - refundTickets;

            System.out.println("---------------------");
            System.out.printf("影片：%s\n", show.getMovie().getName());
            System.out.printf("场次ID：%d，放映厅：%s，时间：%s\n",
                    show.getId(), show.getHall(), sdf.format(show.getTime()));
            System.out.printf("单价：%.2f元\n", show.getPrice());
            System.out.printf("销售票数：%d张\n", soldTickets);
            System.out.printf("退票数：%d张\n", refundTickets);
            System.out.printf("退票金额：%.2f元\n", refundAmount);
            System.out.printf("总票价（销售额）：%.2f元\n", totalPrice);
        }
        System.out.println("---------------------");
    }

    // 查看当周销售数据
    private void viewWeeklySales() {
        System.out.println("\n=== 当周销售数据 ===");
        Date now = new Date();
        Calendar cal = Calendar.getInstance();
        cal.setTime(now);
        cal.setFirstDayOfWeek(Calendar.MONDAY); // 以周一为一周的第一天

        // 当周时间范围：周一00:00:00 至 周日23:59:59
        cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
        cal.set(Calendar.HOUR_OF_DAY, 0);
        cal.set(Calendar.MINUTE, 0);
        cal.set(Calendar.SECOND, 0);
        Date start = cal.getTime();

        cal.add(Calendar.DAY_OF_WEEK, 6);
        cal.set(Calendar.HOUR_OF_DAY, 23);
        cal.set(Calendar.MINUTE, 59);
        cal.set(Calendar.SECOND, 59);
        Date end = cal.getTime();

        List<SaleRecord> weeklySales = getSalesInRange(start, end);
        if (weeklySales.isEmpty()) {
            System.out.println("当周无销售数据");
            return;
        }

        // 统计总数据
        int totalTickets = weeklySales.size();
        int refundTickets = 0;
        double refundAmount = 0;
        double totalPrice = 0;

        for (SaleRecord record : weeklySales) {
            totalPrice += record.getPrice();
            if (record.isRefunded()) {
                refundTickets++;
                refundAmount += record.getRefundAmount();
            }
        }
        int soldTickets = totalTickets - refundTickets;

        System.out.printf("统计时间范围：%s 至 %s\n", sdf.format(start), sdf.format(end));
        System.out.println("---------------------");
        System.out.printf("总销售票数：%d张\n", soldTickets);
        System.out.printf("总销售金额：%.2f元\n", totalPrice);
        System.out.printf("总退票数：%d张\n", refundTickets);
        System.out.printf("总退票金额：%.2f元\n", refundAmount);
        System.out.printf("总票价（总销售额）：%.2f元\n", totalPrice);
        System.out.println("---------------------");
    }

    // 查看当月销售数据
    private void viewMonthlySales() {
        System.out.println("\n=== 当月销售数据 ===");
        Date now = new Date();
        Calendar cal = Calendar.getInstance();
        cal.setTime(now);

        // 当月时间范围：1日00:00:00 至 月末23:59:59
        cal.set(Calendar.DAY_OF_MONTH, 1);
        cal.set(Calendar.HOUR_OF_DAY, 0);
        cal.set(Calendar.MINUTE, 0);
        cal.set(Calendar.SECOND, 0);
        Date start = cal.getTime();

        cal.set(Calendar.DAY_OF_MONTH, cal.getActualMaximum(Calendar.DAY_OF_MONTH));
        cal.set(Calendar.HOUR_OF_DAY, 23);
        cal.set(Calendar.MINUTE, 59);
        cal.set(Calendar.SECOND, 59);
        Date end = cal.getTime();

        List<SaleRecord> monthlySales = getSalesInRange(start, end);
        if (monthlySales.isEmpty()) {
            System.out.println("当月无销售数据");
            return;
        }

        // 统计总数据
        int totalTickets = monthlySales.size();
        int refundTickets = 0;
        double refundAmount = 0;
        double totalPrice = 0;

        for (SaleRecord record : monthlySales) {
            totalPrice += record.getPrice();
            if (record.isRefunded()) {
                refundTickets++;
                refundAmount += record.getRefundAmount();
            }
        }
        int soldTickets = totalTickets - refundTickets;

        System.out.printf("统计时间范围：%s 至 %s\n", sdf.format(start), sdf.format(end));
        System.out.println("---------------------");
        System.out.printf("总销售票数：%d张\n", soldTickets);
        System.out.printf("总销售金额：%.2f元\n", totalPrice);
        System.out.printf("总退票数：%d张\n", refundTickets);
        System.out.printf("总退票金额：%.2f元\n", refundAmount);
        System.out.printf("总票价（总销售额）：%.2f元\n", totalPrice);
        System.out.println("---------------------");
    }

    // 获取指定时间范围内的销售记录
    private List<SaleRecord> getSalesInRange(Date start, Date end) {
        List<SaleRecord> result = new ArrayList<>();
        for (SaleRecord record : saleRecords) {
            Date saleTime = record.getSaleTime();
            if (saleTime.after(start) && saleTime.before(end)) {
                result.add(record);
            }
        }
        return result;
    }

    // 经理主菜单（添加了查看销售数据选项）
    public void showManagerMenu() {
        while (currentManager != null) {
            System.out.println("\n=== 经理操作菜单 ===");
            System.out.println("1. 退出登录");
            System.out.println("2. 添加影片");
            System.out.println("3. 修改影片");
            System.out.println("4. 删除影片");
            System.out.println("5. 查询影片");
            System.out.println("6. 增加场次");
            System.out.println("7. 修改场次");
            System.out.println("8. 删除场次");
            System.out.println("9. 列出场次");
            System.out.println("10. 自动排片");
            System.out.println("11. 查看销售数据"); // 新增选项
            System.out.print("请选择操作：");

            try {
                int choice = Integer.parseInt(scanner.nextLine().trim());
                switch (choice) {
                    case 1:
                        currentManager = null;
                        System.out.println("已退出登录");
                        break;
                    case 2:
                        addMovie();
                        break;
                    case 3:
                        updateMovie();
                        break;
                    case 4:
                        deleteMovie();
                        break;
                    case 5:
                        queryMovie();
                        break;
                    case 6:
                        addShow();
                        break;
                    case 7:
                        updateShow();
                        break;
                    case 8:
                        deleteShow();
                        break;
                    case 9:
                        listShows();
                        break;
                    case 10:
                        autoArrangeShows();
                        break;
                    case 11: // 新增选项处理
                        viewSalesData();
                        break;
                    default:
                        System.out.println("无效选择（1-11）");
                }
            } catch (NumberFormatException e) {
                System.out.println("请输入有效数字");
            }
        }
    }

    // Getter和Setter
    public void setCurrentManager(User loginUser) {
        this.currentManager = loginUser;
    }

    public List<Movie> getMovies() {
        return new ArrayList<>(movies); // 返回副本防止外部修改
    }

    public Show[] getShows() {
        return shows.toArray(new Show[0]);
    }

    public List<SaleRecord> getSaleRecords() {
        return new ArrayList<>(saleRecords);
    }

    public void addSaleRecord(SaleRecord record) {
        saleRecords.add(record);
    }
}